package com.skaz.filter;

import com.skaz.util.Collections;
import com.skaz.util.Strings;
import lombok.NoArgsConstructor;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @Author: jungle
 * @Date: 2019/1/23 4:57 PM
 */
@NoArgsConstructor
public class XssFilter implements Filter {

    private List<String> ignorePathList;
    private List<String> ignoreParamValueList;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String ignorePaths = filterConfig.getInitParameter("ignorePath");
        String ignoreParamValues = filterConfig.getInitParameter("ignoreParamValue");
        String[] ignoreParamValueArr;
        if (Strings.isNotBlank(ignorePaths)) {
            ignoreParamValueArr = ignorePaths.split(",");
            this.ignorePathList = Arrays.asList(ignoreParamValueArr);
        }

        if (Strings.isNotBlank(ignoreParamValues)) {
            ignoreParamValueArr = ignoreParamValues.split(",");
            this.ignoreParamValueList = Arrays.asList(ignoreParamValueArr);
            if (!this.ignoreParamValueList.contains("samlp:LogoutRequest")) {
                this.ignoreParamValueList.add("samlp:LogoutRequest");
            }
        } else {
            this.ignoreParamValueList = new ArrayList();
            this.ignoreParamValueList.add("samlp:LogoutRequest");
        }

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uriPath = ((HttpServletRequest) request).getRequestURI();
        if (this.isIgnorePath(uriPath)) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(new XssRequestWrapper((HttpServletRequest) request), response);
        }
    }

    @Override
    public void destroy() {

    }

    private boolean isIgnorePath(String servletPath) {
        if (Strings.isBlank(servletPath)) {
            return true;
        } else if (Collections.isEmpty(this.ignorePathList)) {
            return false;
        } else {
            Iterator i$ = this.ignorePathList.iterator();

            String ignorePath;
            do {
                if (!i$.hasNext()) {
                    return false;
                }

                ignorePath = (String) i$.next();
            } while (!servletPath.contains(ignorePath));

            return true;
        }
    }
}
